﻿using DAL;
using IService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Model;
using Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WMS.Controllers
{
    public class WhStockTakeController : Controller
    {
        private readonly IWhStockTakeDetailService _whStockTakeDetailService;
        private readonly IWhStockTakeService _whStockTakeService;
        private readonly IDictService _dictDataService;
        private readonly IBiWarehouseService _biWarehouseService;
        private readonly AppDbContext _dbContext;
        private readonly IWhInventoryService _inventoryService;
        public WhStockTakeController(
            IWhStockTakeDetailService whStockTakeDetailService,
            IWhStockTakeService whStockTakeService,
            IDictService dictDataService,
            IBiWarehouseService biWarehouseService,
            AppDbContext dbContext,
            IWhInventoryService inventoryService)
        {
            _whStockTakeDetailService = whStockTakeDetailService;
            _whStockTakeService = whStockTakeService;
            _dictDataService = dictDataService;
            _biWarehouseService = biWarehouseService;
            _dbContext = dbContext;
            _inventoryService = inventoryService;
        }



        /// <summary>
        /// 获取指定类型的字典数据（支持盘点结果、自定义字典等）
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetDictDataList(int dictTypeId)
        {
            try
            {
                // 假设_dictDataService.GetDictDataListAsync 可根据dictTypeId查询字典项
                var dictDatas = await _dictDataService.GetDictDataListAsync(dictTypeId);

                var result = dictDatas.Select(d => new
                {
                    code = d.Code,
                    name = d.Name,
                    value = d.Code // 前端下拉框value字段兼容
                }).ToList();

                return Ok(new { code = 200, data = result, msg = "查询成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询字典数据异常：{ex.Message}" });
            }
        }


        /// <summary>
        /// 获取盘点单聚合数据（前端展示用）
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetInventoryAggregateList()
        {
            try
            {
                var data = await _inventoryService.GetInventoryAggregateListAsync();
                return Ok(new { code = 200, data, msg = "查询成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询异常：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取组织机构树（递归构造部门层级）
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetDepartmentTree()
        {
            try
            {
                // 从数据库查询所有组织机构
                var orgList = await _dbContext.SysOrganization.ToListAsync();
                // 从根节点（ParentOrgId=0）开始构造树
                var tree = BuildOrgTree(orgList, 0);
                return Ok(new { code = 200, data = tree, msg = "查询成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询异常：{ex.Message}" });
            }
        }

        /// <summary>
        /// 递归构造组织机构树（适配SysOrganization实体的属性名）
        /// </summary>
        private List<object> BuildOrgTree(List<SysOrganization> orgList, long parentId)
        {
            // 筛选当前父节点下的子机构（使用ParentOrgId匹配）
            var children = orgList.Where(o => o.ParentOrgId == parentId).ToList();
            var tree = new List<object>();

            foreach (var org in children)
            {
                tree.Add(new
                {
                    id = org.OrgId,       // 对应实体的OrgId
                    name = org.OrgName,   // 对应实体的OrgName
                                          // 递归构造子节点（传入当前机构的OrgId作为父ID）
                    children = BuildOrgTree(orgList, org.OrgId)
                });
            }
            return tree;
        }

        /// <summary>
        /// 根据部门ID获取用户列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetUsersByDepartment(long departmentId)
        {
            try
            {
                // 从Users表查询指定部门（OrgId）的用户
                var users = await (from u in _dbContext.Users
                                   join org in _dbContext.SysOrganization
                                   on u.OrgId equals org.OrgId into orgJoin
                                   from org in orgJoin.DefaultIfEmpty() // 左连接，避免用户无部门时查询失败
                                   where u.OrgId == departmentId // 筛选指定部门的用户
                                   select new
                                   {
                                       id = u.UsersId,
                                       name = u.UsersTrueName, // 用户真实姓名
                                       position = "无职位", // 若用户表无职位字段，可留空或自定义
                                       department = org != null ? org.OrgName : "未知部门" // 关联部门名称
                                   }).ToListAsync();

                return Ok(new { code = 200, data = users, msg = "查询成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询异常：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取盘点单号
        /// </summary>
        /// <returns>盘点单号</returns>
        [HttpGet]
        public async Task<IActionResult> GetInventoryNo()
        {
            try
            {
                var inventoryNo = await _whStockTakeService.GetNextInventoryNoAsync();
                return Ok(new { code = 200, data = inventoryNo, msg = "获取成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"获取盘点单号异常：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取盘点类型列表（从数据字典获取）
        /// </summary>
        /// <returns>盘点类型列表</returns>
        [HttpGet]
        public async Task<IActionResult> GetInventoryTypes()
        {
            try
            {
                // 从数据字典查询：dict_type_id=5 对应盘点类型（参考数据字典表）
                var dictDatas = await _dictDataService.GetDictDataListAsync(5);

                // 转换为前端需要的格式（code=字典编码，name=字典名称）
                var types = dictDatas.Select(d => new
                {
                    code = d.Code,
                    name = d.Name
                }).ToList();

                return Ok(new { code = 200, data = types, msg = "查询成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询异常：{ex.Message}" });
            }
        }
        /// <summary>
        /// 获取仓库列
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetWarehouseList()
        {
            try
            {
                // 从仓库服务获取所有仓库数据
                var warehouses = await _biWarehouseService.GetAllAsync();
                // 转换为前端需要的格式（id=仓库ID，name=仓库名称）
                var result = warehouses.Select(w => new
                {
                    id = w.WarehouseId,
                    name = w.WarehouseName
                }).ToList();

                return Ok(new { code = 200, data = result, msg = "查询成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询异常：{ex.Message}" });
            }
        }

        /// <summary>
        /// 根据仓库ID获取库位列表
        /// </summary>
        /// <param name="warehouseId">仓库ID</param>
        /// <returns>库位列表（ID+名称格式）</returns>
        [HttpGet]
        public async Task<IActionResult> GetWarehouseLocations(long warehouseId)
        {
            try
            {
                if (warehouseId <= 0)
                {
                    return Ok(new { code = 400, msg = "仓库ID无效" });
                }
                var locations = _dbContext.WhLocation
                    .Where(l => l.WarehouseId == warehouseId && l.StorageLocationStatus == '1')
                    .OrderBy(l => l.SortOrder)
                    .Select(l => new
                    {
                        id = l.StorageLocationId,
                        name = l.StorageLocationName // 仅返回库位名称，移除编码拼接
                    })
                    .ToListAsync();
                var locationList = await locations;
                return Ok(new { code = 200, data = locationList, msg = "查询成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"获取库位列表异常：{ex.Message}" });
            }
        }

        /// <summary>
        /// 实时查询账面库存（按仓库、货品、库位）
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetBookInventory(long warehouseId, long goodsId, long storageLocationId)
        {
            try
            {
                var bookInventory = await _inventoryService.GetBookInventoryAsync(warehouseId, goodsId, storageLocationId);
                return Ok(new { code = 200, data = bookInventory, msg = "查询成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询异常：{ex.Message}" });
            }
        }

        /// <summary>
        /// 按仓库+库位查询商品（四表联查：仓库→库位→库存（库位明细）→商品）
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetGoodsByWarehouseAndLocation(long warehouseId, long storageLocationId)
        {
            // 新增日志：确认参数是否正确接收
            Console.WriteLine($"接收参数：warehouseId={warehouseId}, storageLocationId={storageLocationId}");
            try
            {
                var result = await _inventoryService.GetGoodsByWarehouseAndLocationAsync(warehouseId, storageLocationId);
                return Ok(new { code = 200, data = result, msg = "查询成功" });
            }
            catch (ArgumentException ex)
            {
                return Ok(new { code = 400, msg = ex.Message });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 检查仓库锁定状态
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> CheckWarehouseLock(long warehouseId)
        {
            try
            {
                // 从仓库服务获取仓库详情
                var warehouse = await _biWarehouseService.GetByIdAsync((int)warehouseId);
                if (warehouse == null)
                {
                    return Ok(new { code = 404, data = false, msg = "仓库不存在" });
                }
                // 判断仓库是否锁定（假设 WarehouseLocked=1 为锁定）
                bool isLocked = warehouse.WarehouseLocked == "1";
                return Ok(new { code = 200, data = isLocked, msg = "查询成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询异常：{ex.Message}" });
            }
        }
        /// <summary>
        /// 盘点单主页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取所有盘点单数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetAll()
        {
            try
            {
                var stockTakes = await _whStockTakeService.GetAll();
                if (stockTakes == null || !stockTakes.Any())
                {
                    return Ok(new { code = 200, data = new List<object>(), msg = "暂无数据" });
                }

                var result = stockTakes.Select(r => new
                {
                    inventoryOrderId = r.InventoryOrderId,
                    inventoryOrderNo = r.InventoryOrderNo,
                    warehouseId = r.WarehouseId,
                    sourceOrderNo = r.SourceOrderNo,
                    inventoryType = r.InventoryType,
                    inventoryStartTime = r.InventoryStartTime,
                    inventoryEndTime = r.InventoryEndTime,
                    operatorBy = r.OperatorBy,
                    operatorDate = r.OperatorDate,
                    inbound = r.Inbound,
                    outbound = r.Outbound,
                    orderStatus = r.OrderStatus,
                    auditorBy = r.AuditorBy,
                    auditorTime = r.AuditorTime,
                    auditorComment = r.AuditorComment,
                    createBy = r.CreateBy,
                    createTime = r.CreateTime,
                    updateBy = r.UpdateBy,
                    updateTime = r.UpdateTime
                }).ToList();

                return Ok(new { code = 200, data = result, msg = "查询成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询异常：{ex.Message}" });
            }
        }

        ///// <summary>
        ///// 详细信息页面
        ///// </summary>
        ///// <param name="id">盘点单ID</param>
        ///// <returns></returns>
        //public ActionResult Details(long id,string pwd)
        //{
        //    ViewBag.InventoryOrderId = id;
        //    return View();
        //}
        ///// <summary>
        ///// 获取盘点单详细信息
        ///// </summary>
        ///// <param name="id">盘点单ID</param>
        /////<returns></returns>
        //[HttpPost]
        //        public async Task<IActionResult> Details(long id)
        //        {
        //            try
        //            {
        //                var stockTake = await _whStockTakeService.GetByIdAsync(id);
        //                if (stockTake != null)
        //                {
        //                     //获取盘点明细
        //                    var stockTakeDetails = await _whStockTakeDetailService.GetByIdAsync(id);
        //                    var details = stockTakeDetails.Where(d => d.IsDelete != "Y").ToList();

        //                    var result = new
        //                    {
        //                         //主单信息
        //                        inventoryOrderId = stockTake.InventoryOrderId,
        //                        inventoryOrderNo = stockTake.InventoryOrderNo,
        //                        warehouseId = stockTake.WarehouseId,
        //                        sourceOrderNo = stockTake.SourceOrderNo,
        //                        inventoryType = stockTake.InventoryType,
        //                        inventoryStartTime = stockTake.InventoryStartTime,
        //                        inventoryEndTime = stockTake.InventoryEndTime,
        //                        operatorBy = stockTake.OperatorBy,
        //                        operatorDate = stockTake.OperatorDate,
        //                        inbound = stockTake.Inbound,
        //                        outbound = stockTake.Outbound,
        //                        orderStatus = stockTake.OrderStatus,
        //                        auditorBy = stockTake.AuditorBy,
        //                        auditorTime = stockTake.AuditorTime,
        //                        auditorComment = stockTake.AuditorComment,
        //                        createBy = stockTake.CreateBy,
        //                        createTime = stockTake.CreateTime,
        //                        updateBy = stockTake.UpdateBy,
        //                        updateTime = stockTake.UpdateTime,

        //                         //明细信息
        //                        stockTakeDetails = details.Select(d => new
        //                        {
        //                            inventoryOrderDetailId = d.InventoryOrderDetailId,
        //                            inventoryOrderId = d.InventoryOrderId,
        //                            goodsCode = d.GoodsCode,
        //                            productUnit = d.ProductUnit,
        //                            bookInventory = d.BookInventory,
        //                            storageLocationId = d.StorageLocationId,
        //                            inventoryQuantity = d.InventoryQuantity,
        //                            profitLossQuantity = d.ProfitLossQuantity,
        //                            referenceUnitPrice = d.ReferenceUnitPrice,
        //                            profitLossAmount = d.ProfitLossAmount,
        //                            isDelete = d.IsDelete,
        //                            createBy = d.CreateBy,
        //                            createTime = d.CreateTime,
        //                            updateBy = d.UpdateBy,
        //                            updateTime = d.UpdateTime,
        //                            attachmentId = d.AttachmentId,
        //                            remarks = d.Remarks
        //                        })
        //                    };

        //                    return Ok(new { code = 200, data = result, msg = "查询成功" });
        //                }
        //                else
        //                {
        //                    return Ok(new { code = 404, msg = "盘点单不存在" });
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                return Ok(new { code = 500, msg = $"查询异常：{ex.Message}" });
        //            }
        //}

        /// <summary>
        /// 创建页面
        ////</summary>
        /// <returns></returns>
        public IActionResult Create()
        {
            return View();
        }

        /// <summary>
        /// 创建盘点单
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] WhStockTakeCreateModel model)
        {
            // 新增日志，查看模型是否为null及验证错误
            if (model == null)
            {
                // 记录日志：模型为null（绑定失败）
                return Ok(new { code = 400, msg = "请求数据不能为空" });
            }
            if (!ModelState.IsValid)
            {
                // 记录验证错误（如字段类型不匹配、必填项缺失等）
                var errors = ModelState.Values.SelectMany(v => v.Errors.Select(e => e.ErrorMessage));
                return Ok(new { code = 400, msg = $"数据验证失败：{string.Join("；", errors)}" });
            }
            try
            {

                Console.WriteLine($"模型是否为null: {model == null}");
                Console.WriteLine($"StockTake是否为null: {model?.StockTake == null}");
                Console.WriteLine($"明细数量: {model?.StockTakeDetails?.Count ?? -1}");
                // 详细检查每个关键对象
                if (model == null)
                {
                    Console.WriteLine("错误: model 为 null");
                    return Ok(new { code = 400, msg = "请求数据不能为空" });
                }

                if (model.StockTake == null)
                {
                    Console.WriteLine("错误: StockTake 为 null");
                    return Ok(new { code = 400, msg = "盘点单主表数据不能为空" });
                }

                // 检查 StockTake 的关键属性
                Console.WriteLine($"InventoryOrderNo: {model.StockTake.InventoryOrderNo}");
                Console.WriteLine($"InventoryType: {model.StockTake.InventoryType}");
                Console.WriteLine($"WarehouseId: {model.StockTake.WarehouseId}");
                Console.WriteLine($"OperatorBy: {model.StockTake.OperatorBy}");

                // 验证必需字段
                var validationErrors = new List<string>();

                if (string.IsNullOrEmpty(model.StockTake.InventoryType))
                {
                    Console.WriteLine("错误: InventoryType 为空");
                    validationErrors.Add("盘点类型");
                }

                if (model.StockTake.WarehouseId <= 0)
                {
                    Console.WriteLine("错误: WarehouseId 无效");
                    validationErrors.Add("仓库");
                }

                if (model.StockTake.OperatorBy <= 0)
                {
                    Console.WriteLine("错误: OperatorBy 无效");
                    validationErrors.Add("经办人");
                }

                if (model.StockTake.InventoryStartTime == default)
                {
                    Console.WriteLine("错误: InventoryStartTime 无效");
                    validationErrors.Add("盘点开始时间");
                }

                if (validationErrors.Any())
                {
                    return Ok(new { code = 400, msg = $"以下字段为必填项：{string.Join("、", validationErrors)}" });
                }

                // 初始化明细列表
                if (model.StockTakeDetails == null)
                {
                    Console.WriteLine("StockTakeDetails 为 null，初始化为空列表");
                    model.StockTakeDetails = new List<WhStockTakeDetail>();
                }

                // 设置创建信息
                var now = DateTime.Now;
                model.StockTake.CreateTime = now;
                model.StockTake.UpdateTime = now;
                model.StockTake.OperatorDate = now;

                // 设置默认值
                if (string.IsNullOrEmpty(model.StockTake.OrderStatus))
                {
                    model.StockTake.OrderStatus = "0";
                }

                model.StockTake.SourceOrderNo = model.StockTake.SourceOrderNo ?? "";
                model.StockTake.AuditorComment = model.StockTake.AuditorComment ?? "";
                model.StockTake.AuditorTime = now;

                Console.WriteLine($"准备创建盘点主单...");

                // 1. 创建盘点主单
                try
                {
                    Console.WriteLine($"调用 _whStockTakeService.CreateAsync...");
                    var result = await _whStockTakeService.CreateAsync(model.StockTake);
                    Console.WriteLine($"创建主单结果: {result}");

                    if (result > 0)
                    {
                        Console.WriteLine($"盘点主单创建成功，ID: {model.StockTake.InventoryOrderId}");

                        // 2. 创建盘点明细
                        if (model.StockTakeDetails.Any())
                        {
                            Console.WriteLine($"开始创建 {model.StockTakeDetails.Count} 条明细");

                            foreach (var detail in model.StockTakeDetails)
                            {
                                try
                                {


                                    // 检查明细关键属性
                                    if (string.IsNullOrEmpty(detail.GoodsCode))
                                    {
                                        Console.WriteLine("错误: 明细 GoodsCode 为空");
                                        continue;
                                    }

                                    detail.InventoryOrderId = model.StockTake.InventoryOrderId;
                                    detail.IsDelete = "N";
                                    detail.CreateTime = now;
                                    detail.UpdateTime = now;

                                    // 设置明细默认值
                                    detail.ProductUnit = detail.ProductUnit ?? "件";
                                    detail.Remarks = detail.Remarks ?? "";

                                    Console.WriteLine($"调用 _whStockTakeDetailService.CreateAsync...");
                                    await _whStockTakeDetailService.CreateAsync(detail);
                                    Console.WriteLine($"明细创建成功");
                                }
                                catch (Exception detailEx)
                                {
                                    Console.WriteLine($"创建明细失败 - 货品 {detail.GoodsCode}: {detailEx.Message}");
                                    Console.WriteLine($"明细异常堆栈: {detailEx.StackTrace}");
                                    throw;
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine("没有明细需要创建");
                        }

                        return Ok(new { code = 200, msg = "创建成功", data = new { inventoryOrderId = model.StockTake.InventoryOrderId } });
                    }
                    else
                    {
                        Console.WriteLine("盘点单创建失败，返回结果为0");
                        return Ok(new { code = 500, msg = "盘点单创建失败" });
                    }
                }
                catch (Exception serviceEx)
                {
                    Console.WriteLine($"服务层异常: {serviceEx.Message}");
                    Console.WriteLine($"服务层异常堆栈: {serviceEx.StackTrace}");
                    throw;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"创建失败异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");

                // 检查内部异常
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"内部异常: {ex.InnerException.Message}");
                    Console.WriteLine($"内部异常堆栈: {ex.InnerException.StackTrace}");
                }

                return Ok(new { code = 500, msg = $"创建失败：{ex.Message}" });
            }
        }


        /*
        /// <summary>
        /// 修改页面 
        /// </summary>
        /// <param name="id">盘点单ID</param>
        /// <returns></returns>
        public IActionResult Edit(long id)
        {
            ViewBag.InventoryOrderId = id;
            return View();
        }

        /// <summary>
        /// 获取编辑数据
        /// </summary>
        /// <param name="id">盘点单ID</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetEditData(long id)
        {
            try
            {
                var stockTake = await _whStockTakeService.GetByIdAsync(id);
                if (stockTake != null)
                {
                    // 获取盘点明细
                    var stockTakeDetails = await _whStockTakeDetailService.GetByIdAsync(id);
                    var details = stockTakeDetails?.Where(d => d.IsDelete != "Y").ToList() ?? new List<WhStockTakeDetail>();

                    var result = new
                    {
                        // 主单信息
                        stockTake = new
                        {
                            inventoryOrderId = stockTake.InventoryOrderId,
                            inventoryOrderNo = stockTake.InventoryOrderNo,
                            warehouseId = stockTake.WarehouseId,
                            sourceOrderNo = stockTake.SourceOrderNo,
                            inventoryType = stockTake.InventoryType,
                            inventoryStartTime = stockTake.InventoryStartTime,
                            inventoryEndTime = stockTake.InventoryEndTime,
                            operatorBy = stockTake.OperatorBy,
                            operatorDate = stockTake.OperatorDate,
                            inbound = stockTake.Inbound,
                            outbound = stockTake.Outbound,
                            orderStatus = stockTake.OrderStatus,
                            auditorBy = stockTake.AuditorBy,
                            auditorTime = stockTake.AuditorTime,
                            auditorComment = stockTake.AuditorComment,
                            createBy = stockTake.CreateBy,
                            createTime = stockTake.CreateTime,
                            updateBy = stockTake.UpdateBy,
                            updateTime = stockTake.UpdateTime
                        },

                        // 明细信息
                        stockTakeDetails = details.Select(d => new
                        {
                            inventoryOrderDetailId = d.InventoryOrderDetailId,
                            inventoryOrderId = d.InventoryOrderId,
                            goodsCode = d.GoodsCode,
                            productUnit = d.ProductUnit,
                            bookInventory = d.BookInventory,
                            storageLocationId = d.StorageLocationId,
                            inventoryQuantity = d.InventoryQuantity,
                            profitLossQuantity = d.ProfitLossQuantity,
                            referenceUnitPrice = d.ReferenceUnitPrice,
                            profitLossAmount = d.ProfitLossAmount,
                            isDelete = d.IsDelete,
                            createBy = d.CreateBy,
                            createTime = d.CreateTime,
                            updateBy = d.UpdateBy,
                            updateTime = d.UpdateTime,
                            attachmentId = d.AttachmentId,
                            remarks = d.Remarks
                        })
                    };

                    return Ok(new { code = 200, data = result, msg = "查询成功" });
                }
                else
                {
                    return Ok(new { code = 404, msg = "盘点单不存在" });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询异常：{ex.Message}" });
            }
        }

       /// <summary>
        /// 修改提交
        /// </summary>
        /// <param name="id">盘点单ID</param>
        /// <param name="model">盘点单更新模型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Edit(long id, [FromBody] WhStockTakeUpdateModel model)
        {
            try
            {
                if (model == null || model.StockTake == null)
                {
                    return Ok(new { code = 400, msg = "请求数据不能为空" });
                }

                // 验证ID一致性
                if (model.StockTake.InventoryOrderId != id)
                {
                    return Ok(new { code = 400, msg = "ID不匹配" });
                }

                // 设置更新信息
                model.StockTake.UpdateTime = DateTime.Now;

                // 1. 更新盘点主单
                var result = await _whStockTakeService.UpdateAsync(model.StockTake);

                if (result > 0)
                {
                    // 2. 处理盘点明细
                    if (model.StockTakeDetails != null)
                    {
                        // 获取现有明细
                        var existingDetails = await _whStockTakeDetailService.GetByIdAsync(id);
                        var currentDetails = existingDetails.Where(d => d.IsDelete != "Y").ToList();

                        // 处理明细更新
                        foreach (var detail in model.StockTakeDetails)
                        {
                            if (detail.InventoryOrderDetailId == 0)
                            {
                                // 新增明细
                                detail.InventoryOrderId = id;
                                detail.IsDelete = "N";
                                detail.CreateTime = DateTime.Now;
                                detail.UpdateTime = DateTime.Now;
                                await _whStockTakeDetailService.CreateAsync(detail);
                            }
                            else
                            {
                                // 更新现有明细
                                detail.UpdateTime = DateTime.Now;
                                await _whStockTakeDetailService.UpdateAsync(detail);
                            }
                        }

                        // 处理删除的明细（逻辑删除）
                        var updatedDetailIds = model.StockTakeDetails.Where(d => d.InventoryOrderDetailId > 0).Select(d => d.InventoryOrderDetailId);
                        var detailsToDelete = currentDetails.Where(d => !updatedDetailIds.Contains(d.InventoryOrderDetailId));
                        foreach (var detail in detailsToDelete)
                        {
                            detail.IsDelete = "Y";
                            detail.UpdateTime = DateTime.Now;
                            await _whStockTakeDetailService.UpdateAsync(detail);
                        }
                    }

                    return Ok(new { code = 200, msg = "更新成功" });
                }
                else
                {
                    return Ok(new { code = 500, msg = "更新失败" });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"更新异常：{ex.Message}" });
            }
        }*/

        /// <summary>
        /// 删除盘点单
        /// </summary>
        /// <param name="id">盘点单ID</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Delete(long id)
        {
            try
            {
                // 1. 先删除关联的盘点明细（修正修正DbSet名称和属性名）
                var details = await _dbContext.WhStockTakeDetail  // 改为大写开头的WhStockTakeDetail
                    .Where(d => d.InventoryOrderId == id)  // 确保实体中关联ID的属性是InventoryOrderId
                    .ToListAsync();
                _dbContext.WhStockTakeDetail.RemoveRange(details);  // 同样修正此处
                await _dbContext.SaveChangesAsync();

                // 2. 再删除盘点单
                var stockTake = await _whStockTakeService.GetByIdAsync(id);
                if (stockTake == null)
                {
                    return Ok(new { code = 404, msg = "盘点单不存在" });
                }
                var result = await _whStockTakeService.DeleteAsync(id);

                return Ok(new { code = 200, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"删除异常：{ex.Message}" });
            }
        }

        /// <summary>
        /// 更新盘点单状态
        /// </summary>
        /// <param name="id">盘点单ID</param>
        /// <param name="status">状态</param>
        /// <param name="auditorComment">审核意见</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpdateStatus(long id, string status, string auditorComment = "")
        {
            // 添加详细日志
            Console.WriteLine($"=== 开始更新盘点单状态 ===");
            Console.WriteLine($"盘点单ID: {id}, 目标状态: {status}, 审核意见: {auditorComment}");

            // 开启全局事务：盘点单状态更新 + 库存调整
            using var transaction = await _dbContext.Database.BeginTransactionAsync();
            try
            {
                var stockTake = await _whStockTakeService.GetByIdAsync(id);
                if (stockTake == null)
                {
                    Console.WriteLine($"错误：盘点单 {id} 不存在");
                    await transaction.RollbackAsync();
                    return Ok(new { code = 404, msg = "盘点单不存在" });
                }

                Console.WriteLine($"找到盘点单: {stockTake.InventoryOrderNo}, 当前状态: {stockTake.OrderStatus}");

                // 保存原始状态，用于判断是否需要调整库存
                string originalStatus = stockTake.OrderStatus;

                // 更新状态信息
                stockTake.OrderStatus = status;
                stockTake.UpdateTime = DateTime.Now;

                // 如果是审核相关操作，记录审核信息
                if (status == "1" || status == "2" || status == "3")
                {
                    stockTake.AuditorTime = DateTime.Now;
                    stockTake.AuditorComment = auditorComment;
                    // 注意：实际项目中需从登录上下文获取审核人ID，此处暂用默认值，需替换
                    stockTake.AuditorBy = 1; // 替换为真实登录用户ID
                    Console.WriteLine($"设置审核信息 - 时间: {stockTake.AuditorTime}, 审核人: {stockTake.AuditorBy}");
                }

                // 1. 更新盘点单状态
                Console.WriteLine("开始更新盘点单状态...");
                var result = await _whStockTakeService.UpdateAsync(stockTake);
                if (result <= 0)
                {
                    Console.WriteLine("盘点单状态更新失败");
                    await transaction.RollbackAsync();
                    return Ok(new { code = 500, msg = "状态更新失败" });
                }
                Console.WriteLine("盘点单状态更新成功");

                // 2. 审核通过（假设status="3"代表审核通过），执行库存调整
                int adjustCount = 0;
                if (status == "3" && originalStatus != "3")
                {
                    Console.WriteLine("开始执行库存调整...");

                    // 关键修复：确保传入正确的盘点单ID
                    adjustCount = await _inventoryService.AdjustInventoryForStockTakeAsync(id);
                    Console.WriteLine($"库存调整完成，共调整 {adjustCount} 条库存记录");

                    if (adjustCount == 0)
                    {
                        Console.WriteLine("警告：库存调整数量为0，可能没有需要调整的库存记录");
                        // 这里可以进一步检查原因，但不应该回滚事务
                    }
                }
                else
                {
                    Console.WriteLine($"跳过库存调整 - 目标状态: {status}, 原状态: {originalStatus}");
                }

                // 提交事务
                await transaction.CommitAsync();
                Console.WriteLine("事务提交成功");

                return Ok(new { code = 200, msg = "状态更新成功", data = new { adjustCount } });
            }
            catch (Exception ex)
            {
                // 回滚事务
                Console.WriteLine($"发生异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                await transaction.RollbackAsync();
                return Ok(new { code = 500, msg = $"状态更新异常：{ex.Message}" });
            }
        }


        /// <summary>
        /// 盘点单创建模型
        /// </summary>
        public class WhStockTakeCreateModel
        {
            public WhStockTake StockTake { get; set; }
            public List<WhStockTakeDetail> StockTakeDetails { get; set; }
        }

        /// <summary>
        /// 盘点单更新模型
        /// </summary>
        public class WhStockTakeUpdateModel
        {
            public WhStockTake StockTake { get; set; }
            public List<WhStockTakeDetail> StockTakeDetails { get; set; }
        }
    }
}